import tkinter
import customtkinter as CTk
from PIL import Image, ImageTk
from tkinter import ttk
import asist
import json
import customtkinter as CTk
from config import VA_NAME as bot_name
import datetime

speaker_dropdown = 'xenia'


def show_warning():
    messagebox.showwarning("Предупреждение", "Это важное сообщение!")
    root.withdraw()
    password_window = CTk.CTk()
    password_window.title("Ввод парольной фразы")

    voice_button = CTk.CTkButton(password_window, text="Голосовой ввод", command=get_password)
    voice_button.pack(pady=10)

    text_entry = CTk.Entry(password_window, show="*")
    text_entry.pack()

    check_button = tk.Button(password_window, text="Проверить", command=lambda: check_password(text_entry.get()))
    check_button.pack(pady=10)

class MainWindow(CTk.CTk):
    def __init__(self, settings):
        super().__init__()

        self.after(101, lambda: self.iconbitmap(r"C:\Users\Iren\OneDrive\Рабочий стол\20_СБК_Мартынова_ВКР_Код\image\micro1.ico"))
        self.font = CTk.CTkFont(family=settings["family"], size=settings["size"])

        self.protocol("WM_DELETE_WINDOW", self.on_closing)

        tab = CTk.CTkTabview(self)
        tab.pack(padx=10, pady=10, expand=1, fill='both')
        tab._segmented_button.configure(font=self.font)

        chat = tab.add("Чат")
        sett = tab.add("Настройки")

        self.set_wid(sett)
        self.chat_wid(chat)



    def on_closing(self):
        if CTk.get_appearance_mode() == "Светлая":
            default_color_theme = "dark-blue"
        else:
            default_color_theme = "blue"
        with open("settings.json", "r") as f:
            sett = json.load(f)
            passw=sett["password"]
        settings = {
            "appearance_mode": CTk.get_appearance_mode(),
            "default_color_theme": default_color_theme,
            "family": self.font["family"],
            "size": self.font["size"],
            "speaker": speaker_dropdown,
            "password": passw
        }
        with open('settings.json', 'w') as file:
            json.dump(settings, file)
        self.destroy()
        exit()
    def set_wid(self, sett):
        theme_switch = CTk.StringVar(value="Светлая")
        sett.columnconfigure(0, weight=1)
        sett.columnconfigure(1, weight=1)

        def on_switch_change(event):
            if theme_switch.get() == "Светлая":
                switch_th.configure(text="Светлая тема")
                CTk.set_appearance_mode("light")
                CTk.set_default_color_theme("blue")
            else:
                switch_th.configure(text="Темная тема")
                CTk.set_appearance_mode("dark")
                CTk.set_default_color_theme("dark-blue")

        switch_th = CTk.CTkSwitch(sett, text="Светлая тема", variable=theme_switch, onvalue="Светлая",
                                      offvalue="Темная",  switch_width=150, switch_height=25,
                                      fg_color="white", progress_color="gray", button_hover_color="blue",
                                      font=self.font)
        switch_th.grid(row=0, column=0, pady=40)
        switch_th.bind("<ButtonRelease-1>", on_switch_change)

        font_size = CTk.StringVar(value="Средний")

        def on_font_size_change(value):
            if self.winfo_exists():
                if value == 1.0:
                    font_size.set("Маленький")
                    self.font.configure(size=16)
                elif value == 2.0:
                    font_size.set("Средний")
                    self.font.configure(size=24)
                elif value == 3.0:
                    font_size.set("Большой")
                    self.font.configure(size=40)

        slider = CTk.CTkSlider(sett, from_=1, to=3, orientation='horizontal', number_of_steps=2, width=300, height=30,
                                   #fg_color="red", progress_color="green", button_color="yellow", button_hover_color="orange"
                               command=on_font_size_change)
        slider.grid(row=1, column=0, pady=40, sticky="nsew")

        font_size_label = CTk.CTkLabel(sett, text="Размер шрифта", font=self.font)
        font_size_label.grid(row=1, column=1, pady=40, sticky="nsew")


        speaker_options = ["xenia", "baya", "kseniya", "aidar", "random"]
        speaker_dropdown = CTk.CTkComboBox(sett, values=speaker_options)
        speaker_dropdown.grid(row=2, column=0, pady=10, sticky="new")
        speaker_dropdown.configure(font=self.font)

        speaker_label = CTk.CTkLabel(sett, text="Выбор озвучки", font=self.font)
        speaker_label.grid(row=2, column=1, pady=20, sticky="nsew")


    def chat_wid(self, chat):

        chat.grid_columnconfigure(0, weight=1)
        chat.grid_rowconfigure(0, weight=1)

        self.chat_widget = CTk.CTkTextbox(chat, width=600, height=600,state="disabled")
        self.chat_widget.grid(row=0, column=0, sticky="nsew")
        self.chat_widget.configure(cursor="arrow")

        textbox_scrollbar = CTk.CTkScrollbar(chat, command=self.chat_widget.yview)
        #textbox_scrollbar.grid(row=0, column=1, sticky="ns")
        self.chat_widget.configure(yscrollcommand=textbox_scrollbar.set)

        bottom_l = CTk.CTkLabel(chat, height=10, text='')
        bottom_l.grid(row=1, column=0)

        self.msg_entry = CTk.CTkEntry(bottom_l, font=self.font, width=650)
        self.msg_entry.focus()
        self.msg_entry.grid(row=1, column=0, padx=5, pady=5)
        self.msg_entry.bind("<Return>", self._on_enter_pressed)

        send_btn = CTk.CTkButton(bottom_l, text="Отправить запрос", font=self.font, width=20, height=30,
                             command=lambda: self._on_enter_pressed(None))
        send_btn.grid(row=1, column=1)

    def _on_enter_pressed(self, event):
        msg = self.msg_entry.get()
        self._insert_message(msg, "Вы")

    def _insert_message(self, msg, sender):
        if not msg:
            return
        current_time = datetime.datetime.now().strftime("%H:%M")

        self.chat_widget.configure(state="normal")
        self.msg_entry.delete(0, "end")

        if sender == "Вы":
            msg1 = f"{sender}: {msg} \n"
            self.chat_widget.tag_config("user", relief="ridge", borderwidth=2, spacing1=10,
                                        spacing2=5, spacing3=10, justify="right")
            self.chat_widget.insert("end", msg1, "user")
            self.chat_widget.tag_add("user", "end-1c linestart", "end-1c lineend")

            self.chat_widget.insert("end", f"({current_time})\n", "time")
            self.chat_widget.tag_config("time", foreground="gray",  justify="left")


            self.chat_widget.configure(font=self.font, state="disabled")
            self.chat_widget.see("end")
        else:

            msg2 = f"  {bot_name.capitalize()}: {msg} \n"

            self.chat_widget.tag_config("bot", relief="ridge", borderwidth=2,
                                        spacing1=15, spacing2=15, spacing3=10, justify="left")

            self.chat_widget.insert("end", msg2, "bot")
            self.chat_widget.tag_add("bot", "end-1c linestart", "end-1c lineend")

            self.chat_widget.insert("end", f"({current_time})\n", "time")
            self.chat_widget.tag_config("time", foreground="gray",  justify="right")
            self.chat_widget.tag_add("time", "end-1c linestart", "end-1c lineend")

        self.chat_widget.configure(font=self.font, state="disabled")

        self.chat_widget.see("end")
